/**
 * @Author: jipeng.Li
 * @Date: 2021-04-20 08:22:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-04-20 11:54:21
 * @Description: 共享记录
 */
import React, { Component } from 'react';
import { Image, SafeAreaView, StyleSheet, TouchableOpacity } from 'react-native';
import { iconShare } from '@/images';
import { mainBgColorLightGray, px2dp, screenWidth } from '@/styles';
import { msg } from '@/common';
import wlRepair from '@/api/repair';
import ShareCard from './components/share-card';
import XmList from '../../components/XmList';

export default class ShareRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recordList: [],
      pageNo: 1,
      pageSize: 4,
      hasMorePage: true,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      isLoading: false,
      cardData: {}
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { cardData } = params;
    this.setState({ cardData }, () => {
      this.loadData();
    });
  }

  componentWillUnmount() {
    msg.emit('setUpWlRepairQrCodeInterval');
  }

  render() {
    const { isLoading, recordList, cardData, showFoot } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        {/* 共享按钮 */}
        {(cardData.accountCarownerId !== '') && this.renderShareBtn()}
        <XmList
          sources={recordList}
          renderItem={this.renderRecordItem}
          style={styles.container}
          isLoading={isLoading}
          onDropdownRefresh={this.loadData}
          onPullUpMore={this.LoadMore}
          singleKey={item => `recordList${item.id}`}
          showFoot={showFoot}
        />
      </SafeAreaView>
    );
  }

  // 分享按钮
  renderShareBtn = () => {
    const { cardData } = this.state;
    return (
      <TouchableOpacity
        style={styles.shareBtn}
        activeOpacity={0.8}
        onPress={() => {
          msg.emit('router: goToNext', {
            routeName: 'WlRepairShareAuthorize',
            cardData
          });
        }}
      >
        <Image
          source={iconShare}
          style={styles.shareImage}
        />
      </TouchableOpacity>
    );
  }

  // 渲染记录元素
  renderRecordItem = ({ item }) => {
    function add() {
      let sum = 0;
      for (let i = 0; i < arguments.length; i++) {
        sum += parseFloat(arguments[i] ?? 0);
      }
      sum = sum.toFixed(2) * 1000 / 1000;
      return sum;
    }

    let cardData = {
      disabled: item.isRecovery === 'Y',
      isOneself: item.type === 2,
      balance: item.isQuota === 'Y' ? `上限：¥${item.authBalance}` : '',
      name: item.driverName,
      mobil: item.driverMobil,
      carNo: item.carNo || '',
      total: add(item.total, item.mallBuy),
      useNumber: item.number,
      empowerNum: item.isLimit === 'Y' ? `已用次数(余${item.empowerNum}次)` : '不限次数',
      endTime: item.empowerEndTime,
      startTime: item.empowerStartTime,
      recoveryClick: () => this.recovery(item.id)
    };
    return (
      <ShareCard
        {...cardData}
      />
    );
  }

  // 回收按钮方法
  recovery = (id) => {
    msg.emit('app:messageBox', {
      isVisible: true,
      title: '确认回收授权？',
      text: '维修卡回收后，该用户将无法再次使用维修卡',
      okText: '确定',
      cancelText: '取消',
      okFn: () => {
        wlRepair.recycling({ id }).then(res => {
          if (res.success) {
            this.loadData();
          } else {
            msg.emit('app:messageBox', {
              isVisible: true,
              title: '提示',
              text: res.msg || '回收失败，请重试',
              okText: '确定',
              isClickBg: false,
            });
          }
        });
      },
    });
  }

  // 下拉刷新
  loadData = () => {
    this.setState({
      isLoading: true,
      pageNo: 1,
      recordList: [],
      showFoot: 0
    }, () => {
      this.pageOwnerAuthorization('dropdown');
    });
  }

  // 上拉加载更多
  LoadMore = () => {
    this.setState({ showFoot: 2 }, () => this.pageOwnerAuthorization('pullMore'));
  }

  /**
   * 接口
   */
  pageOwnerAuthorization = (type) => {
    const { recordList, pageNo, pageSize, cardData } = this.state;
    let newRecordList = [];
    wlRepair.pageOwnerAuthorization({
      id: cardData.accountCarownerId,
      pageNo: pageNo,
      pageSize: pageSize
    }).then(res => {
      if (res.success) {
        const { records, pages } = res.data;
        if (type === 'dropdown') {
          this.setState({ recordList: records });
        }
        if (type === 'pullMore') {
          if (pageNo > pages) {
            this.setState({ showFoot: 1 });
            return;
          }
          newRecordList = [...recordList, ...records];
          this.setState({ recordList: newRecordList });
        }
        this.setState({ isLoading: false, pageNo: pageNo + 1 });
      } else {
        msg.emit('app:tip', { text: res.msg });
        this.setState({ isLoading: false, recordList: [] });
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    padding: px2dp(20),
  },
  shareBtn: {
    zIndex: 99,
    position: 'absolute',
    bottom: px2dp(40),
    left: screenWidth / 2 - px2dp(154),
  },
  shareImage: {
    width: px2dp(308),
    height: px2dp(144)
  }
});
